<?php
/**
 * Created by PhpStorm.
 * User: ADMIN
 * Date: 2021/6/6
 * Time: 21:03
 */
namespace app\api\controller;

use app\common\controller\Api;
use xing\payment\drive\PayFactory;

class Order extends Api
{
    protected $noNeedLogin = ['wxnotify'];
    protected $noNeedRight = ['*'];

    /**
     * 创建订单
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $postData = json_decode(request()->getContent(), true);
        // 用户信息
        $user = $this->auth->getUserinfo();
        $postData['user_id'] = $user['user_id'];

        // 数据验证
        $result = $this->validate($postData, 'Order');
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }

        $data = \app\common\model\Order::createOrder($postData, $user);
        $data['timeStamp'] = strval($data['timeStamp']);
        $this->success('下单成功', $data);
    }

    /**
     * 支付回调
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function wxnotify()
    {
        // 支付配置
        $site = config('site');

        // 微信配置
        $config = [
            'appId' => $site['applets_appid'],
            'mchId' => $site['mchId'],
            'notifyUrl' => request()->domain().'/homeapi/wxnotify',
            // 请换成你自己的相应的文证书件地址
            'SSL_CERT_PATH' =>  request()->domain().'/wxpem/apiclient_cert.pem',
            'SSL_KEY_PATH' => request()->domain().'/wxpem/apiclient_key.pem',
            'key'=>$site['mchkey'],// 支付秘钥
        ];
        /* 初始化 */
        $payName = 'weChatPay'; // 支付驱动代码
        $payInstance = PayFactory::getInstance($payName)->init($config); //支付驱动 的配置，详情看配置篇，小程序需要在微信支付配置的基础上多加openId
        $post = $payInstance->getNotifyParams();
        trace(date('Y-m-d H:i:s')."支付回调数据：".json_encode($post)."\r\n\r\n",'info');
        // 支付成功
        if($post['result_code'] = 'SUCCESS' && $post['return_code'] = 'SUCCESS')
        {
            $order = db('order')
                ->alias('a')
                ->join('goods b', 'a.goods_id = b.id')
                ->join('user c', 'a.user_id = c.id')
                ->where("a.ordersn='{$post['out_trade_no']}'")
                ->field('b.total, a.user_id, a.goods_category_id, c.money, a.user_id, c.mobile, a.goods_id, b.level, c.level as ulevel, c.level_duedate')
                ->find();
            if(!empty($order))
            {
                $orderData = [
                    'status' => '3',
                    'paytime' => time(),
                    'completetime' => time(),
                ];
                db('order')
                    ->where('ordersn', $post['out_trade_no'])
                    ->update($orderData);

                // 金豆充值
                if($order['goods_category_id']==2)
                {
                    // 金豆变更记录
                    $userMoneyLog = [
                        'user_id' => $order['user_id'],
                        'money' => $order['total'],
                        'before' => $order['money'],
                        'after' => $order['money']+$order['total'],
                        'memo' => "用户".$order['mobile']."购买商品".$order['goods_id']."增加金豆".$order['total'],
                        'createtime' => time(),
                    ];
                    db('user_money_log')
                        ->insert($userMoneyLog);
                    
                    // 金豆数量修改
                    db('user')
                        ->where('id', $order['user_id'])
                        ->setInc('money', $order['total']);
                }
                elseif($order['goods_category_id'] == 1)
                {
                    // 会员开通
                    $level_duedate = !empty($order['level_duedate']) ? $order['level_duedate']+$order['total']*24*3600 : time()+$order['total']*24*3600;

                    // 会员等级变更记录
                    $userLevelLog = [
                        'user_id' => $order['user_id'],
                        'before' => $order['ulevel'],
                        'after' => $order['level'],
                        'memo' => "用户".$order['mobile']."购买商品".$order['goods_id']."升级",
                        'createtime' => time(),
                        'duedate' => $level_duedate,
                    ];
                    db('user_level_log')
                        ->insert($userLevelLog);

                    $userData = [
                        'level' => $order['level'],
                        'level_duedate' => $level_duedate,
                    ];
                    db('user')
                        ->where('id', $order['user_id'])
                        ->update($userData);
                }
            }

        }
        echo 'success';
    }

    /**
     * 订单列表
     * 排除未支付的
     */
    /*public function list()
    {
        $postData = json_decode(request()->getContent(), true);

        // 数据验证
        $result = $this->validate($postData, 'OrderList');
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }

        $data = \app\common\model\Order::getList($postData);
        $this->success('查询成功', $data);
    }*/

}